<template>
  <span>
    <sys-notify
      :msg-data="msgData"
      :msg-count="msgCount"
      :msg-exist="msgExist"
      :total="total"
      :current-page.sync="currentPage"
      separate
      scroller
      @link-click="linkClick"
      @more-click="moreClick"
      @del-msg="delMsg"
      @pageChange="pageChange"
    />
  </span>
</template>
<script>
// import SysNotify from 'components/sys-notify';
import { Date2String, Date2Week, isAuthorizedUrl } from 'utils/funcs';
import { util, cacheUtil } from 'utils/util'; // 工具类
import _ from 'lodash';
// import Message from 'components/message';
import Stomp from 'stompjs';
import SockJS from 'sockjs-client';

export default {
  name: 'SysMsg',
  cName: '系统消息',
  componentName: 'SysMsg',
  components: {
    // SysNotify
  },
  data() {
    return {
      total: 1,
      currentPage: 1,
      stompClient: null,
      retry: 3, // 重连次数
      count: 1,
      retryTimeout: 10000, // 重连超时时间
      msgCount: 0,
      msgExist: 0,
      msgData: [
      ]
    };
  },
  mounted() {
    // 启动一个ws协议连接
    this.connect();
    this.getSysMsg();
  },
  methods: {
    linkClick(item) {
      util.request({
        serviceId: '40000007',
        tranCode: 'MSGPLAT007',
        model: { 'modifyList': [{ 'c_pk_id': item.c_pk_id }] },
        onSuccess: (jqXHR, textStatus, data) => {
          this.getSysMsg();
        },
        onError: (jqXHR, textStatus, data) => {
          Message.error(data.message);
          this.msgData = [];
        }
      });
    },
    moreClick(item) {
      console.log('moreClick', item);
    },
    delMsg(item) {
      this.msgData.splice(this.msgData.indexOf(item), 1);
      util.request({
        serviceId: '40000007',
        tranCode: 'MSGPLAT007',
        model: { 'deleteList': [{ 'c_pk_id': item.c_pk_id }] },
        onSuccess: (jqXHR, textStatus, data) => {
          this.getSysMsg();
        },
        onError: (jqXHR, textStatus, data) => {
          Message.error(data.message);
          this.msgData = [];
        }
      });
    },
    /**
       * 获取当前用户系统消息
       */
    getSysMsg() {
      console.log('获取当前用户系统消息');
      const { currentPage } = this;
      this.msgExist = 0;
      this.msgCount = 0;
      util.request({
        serviceId: '40000006',
        tranCode: 'MSGPLAT006',
        model: {},
        pageNo: currentPage,
        pageSize: 5,
        onSuccess: (jqXHR, textStatus, data) => {
          this.msgExist = data.total;
          this.total = data.model.pager && data.model.pager.total || 0;
          this.msgCount = data.model.unread || 0;
          this.msgData = data.model.list.map((obj) => {
            // if('0' === obj.c_status){
            //   this.msgCount ++
            // }
            return {
              c_pk_id: obj.c_pk_id,
              c_msg_text: obj.c_msg,
              c_doc_no: obj.c_rel_num,
              d_msg_date: obj.d_send_time,
              c_status: obj.c_status
            };
          });
        },
        onError: (jqXHR, textStatus, data) => {
          Message.error(data.message);
          this.msgData = [];
        }
      });
    },
    pageChange(val) {
      this.currentPage = val;
      console.log('分页功能', val);
      this.getSysMsg();
    },
    connect() {
      if (!this.stompClient || !this.stompClient.connected) {
        // 建立连接对象
        const socket = new SockJS('/msg-plat-service/ws');

        // 获取STOMP子协议的客户端对象
        this.stompClient = Stomp.over(socket);
        // 定义客户端的认证信息,按需求配置
        const headers = {
          Authorization: cacheUtil.getCookies('Authorization')
        };
        // 登录的人员代码
        const operCode = util.getOper().c_oper_code;
        // 向服务器发起websocket连接
        this.stompClient.connect(headers, () => {
          this.count = 1;
          const subscribeUrl = `/topic/${operCode}`;
          this.stompClient.subscribe(subscribeUrl, (msg) => { // 订阅服务端提供的某个topic
            // 收到针对当前用户的消息则直接请求一次后端, 防抖3s之内执行最后一次
            console.log('消息msg--------：', msg);
            const func = _.debounce(this.getSysMsg, 3000);
            func();
          }, headers);
        }, (err) => {
          console.log('socket失败', err);
          // 连接发生错误时的处理函数
          this.reconnect();
        });
      }
    },
    reconnect() {
      const func = _.debounce(this.connect, this.retryTimeout);
      if (this.count++ <= this.retry) {
        func();
      }
    }
  }
};
</script>
